#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HeilongjiangjmssFujinPolicy(BaseTaxPolicySpider):
    name = 'heilongjiang_jmss_fujin_policy'
    
    province = '黑龙江省'
    city: str = "佳木斯市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    custom_settings = {"DOWNLOAD_TIMEOUT": 60}

    @classmethod
    def update_settings(cls, settings) -> None:
        new_settings = {
            **(cls.custom_settings or {}),
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['富锦市人民政府', "富锦市", "https://www.fujin.gov.cn/f/listGovern-28933.html"],
            ['富锦市人民政府', "富锦市", "https://www.fujin.gov.cn/f/listGovern-28934.html"],
            ['富锦市人民政府', "富锦市", "https://www.fujin.gov.cn/f/listGovern-32450.html"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_url, meta={'item': item}, dont_filter=True)

    def parse_url(self, response, **kwargs):
        meta = response.meta
        meta['url'] = response.url
        url = response.url.replace("Govern-", "GovernNews-")
        yield response.follow(url, callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//table//tr/td/a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::td[string-length(string(.))>=5] | "
                "//div[contains(@class, 'zwgk-list-type2')]//div//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::div[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url']).replace('/op_', '/cn/op_cn_')
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下一页' in response.text:
                total = response.xpath(""".""").re_first(r"""共\s*(\d+)\s*条""")
                if total is None:
                    total = response.xpath('//a[text()="尾页"]/@href').re_first(r"/(\d+)\.htm")
                total_page = math.ceil(int(total) / 20)
                print(response.url, total, "page:", total_page)
                for page_num in range(2, total_page + 1):
                    url = response.url + f"?pageNo={page_num}&pageSize=20"
                    yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("//*[contains(.//text(), '发布时间：')]//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl heilongjiang_jmss_fujin_policy".split())
